import React, {useEffect, useState, useRef} from 'react'
import {Button, Space, Tag} from 'antd'
import {ArrowDownOutlined} from '@ant-design/icons'

import {history, connect} from 'umi'

import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'
import {getSummaryListPage} from '@/service/marketing/awardSettlement/subsidy'
import {getOrderType} from '@/service/marketing/commodity'
import {translateDataToTree} from '@/utils/common/index'
import {getMainCompanyList, getCompany} from '@/service/system/company'
import {formatDate} from '@/utils/common/dateFilter'
import {downloadDocumentUrl} from '@/service/common/download'
import {getAllCitys} from '@/service/common'

import {getDict} from '@/service/common/dict'
import 'moment/locale/zh-cn'

const formItemLayout = {
	labelCol: {flex: '90px'},
	wrapperCol: {flex: '1'},
}
const subsidy = (props: {user: any}) => {
	const {orgId} = props.user
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)

	const [citysList, setCitysList] = useState([])
	const [orderType, setOrderType] = useState([])
	const [mainCompany, setMainCompanyList] = useState([])
	const [orgSource, setOrgSource] = useState<any>([])

	const [dataSourse, setDataSourse] = useState([])
	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])
	const [dict, setDict] = useState({
		orderLocation: [],
	})
	// 字典查询
	useEffect(() => {
		// 初始化
		getDict(
			{
				dictKeys: ['orderLocation'],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])

	// 获取主体数据
	const onMainCompanyeListFun = () => {
		getMainCompanyList().then((res: any) => {
			if (res?.success) {
				setMainCompanyList(res.data)
			}
		})
	}

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
			}
		})
	}
	useEffect(() => {
		onOrgFun()
	}, [orgId])

	/** 获取城市列表 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res?.data)
			}
		})
	}

	/** 获取订单类型列表 */
	const getOrderTypeFun = () => {
		getOrderType().then((res: any) => {
			if (res?.success) {
				setOrderType(() => res?.data)
			}
		})
	}

	useEffect(() => {
		getCitysFun()
		getOrderTypeFun()
		onMainCompanyeListFun()
	}, [])

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getSummaryListPage({
			...params,
			...searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(() => res?.data?.records)
					setTotal(() => res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	const columns: any = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: any, record: any, index: any) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '补贴月份',
			dataIndex: 'subsidyMonth',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '提车月份',
			dataIndex: 'collectionMonth',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '城市名称',
			dataIndex: 'cityName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '所属主体名称',
			dataIndex: 'principalName',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '公司',
			dataIndex: 'corporateName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '司机姓名',
			dataIndex: 'driverName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '司机ID',
			dataIndex: 'driverId',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '订单位置',
			dataIndex: 'orderLocation',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: number, record: any) => (
				<>
					{text
						? dict?.orderLocation?.map(
								(item: {
									dictKey: number
									dictValue: string
								}) => {
									if (
										Number(item?.dictKey) === Number(text)
									) {
										return (
											<Tag
												color="processing"
												key={record?.id}>
												{item?.dictValue}
											</Tag>
										)
									}
									return ''
								},
						  )
						: '--'}
				</>
			),
		},
		{
			title: '订单类型',
			dataIndex: 'orderType',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: number, record: any) => (
				<>
					{orderType?.map((item: {code: number; name: string}) => {
						if (Number(item?.code) === Number(text)) {
							return (
								<Tag color="processing" key={record?.id}>
									{item?.name}
								</Tag>
							)
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '订单标签',
			dataIndex: 'orderLabel',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '订单号',
			dataIndex: 'orderNo',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '车牌号',
			dataIndex: 'carNo',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '车型简称',
			dataIndex: 'brandName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any, record: any) => (
				<>{`${record?.brandName ? record?.brandName : '--'}/${
					record?.modelName ? record?.modelName : '--'
				}`}</>
			),
		},
		{
			title: '网约车订单品类',
			dataIndex: 'orderCategory',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '提车日期',
			dataIndex: 'dateOfCollection',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => (
				<>{text ? moment(text).format('YYYY-MM-DD') : '--'}</>
			),
		},
		{
			title: '租期',
			dataIndex: 'leaseTerm',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},

		{
			title: '预计结束日期',
			dataIndex: 'estimatedEndDate',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => (
				<>{text ? moment(text).format('YYYY-MM-DD') : '--'}</>
			),
		},
		{
			title: '订单实际结束日期',
			dataIndex: 'actualOrderEndDate',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => (
				<>{text ? moment(text).format('YYYY-MM-DD') : '--'}</>
			),
		},
		{
			title: '押金（元）',
			dataIndex: 'deposit',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '首付（元）',
			dataIndex: 'downPayments',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '月租金（元）',
			dataIndex: 'monthlyRent',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '月服务费（元）',
			dataIndex: 'monthlyServiceFee',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '月总租金（租金+服务费）（元）',
			dataIndex: 'totalMonthlyRent',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},

		{
			title: '尾款（元）',
			dataIndex: 'balancePayment',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '是否有奖励达成',
			dataIndex: 'achievedOrNot',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <Tag color="processing">{text || '--'}</Tag>,
		},
		{
			title: '延租天数',
			dataIndex: 'daysOfExtension',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{Number(text) >= 0 ? text : '--'}</>,
		},
		{
			title: '延租金额（元）',
			dataIndex: 'moneyOfYz',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '免租金额（元）',
			dataIndex: 'moneyOfMz',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},

		{
			title: '返现金额（元）',
			dataIndex: 'moneyOfFx',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},

		{
			title: '实物金额（元）',
			dataIndex: 'moneyOfSw',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '补贴合计（元）',
			dataIndex: 'moneyOfTotal',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text: any, record: any) => (
				<div>
					<Permissions permissionID="amc_merchantCenter_awardSettlement_driverDetailList_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname:
										'/merchantCenter/awardSettlement/subsidy/view',
									query: {
										ids: record?.ids,
										orderNo: record?.orderNo,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
				</div>
			),
		},
	]

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [searchData])

	// 搜索
	const onFinish = (values: any) => {
		const subsidyMonth = values?.subsidyMonth
			? formatDate(values?.subsidyMonth, 'YYYY-MM')
			: null
		const cityId = values?.city ? values?.city[1] : null
		const search = {
			...values,
			subsidyMonth,
			cityId,
		}
		delete search?.city
		setSearchData(search)
	}

	// 搜索重置
	const onReset = () => {
		setSearchData({})
	}
	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'time',
						key: 'subsidyMonth',
						name: 'subsidyMonth',
						subtype: 'month',
						label: '补贴月份',
					},
					{
						type: 'cascader',
						label: '城市名称',
						name: 'city',
						key: 'city',
						fieldNames: {
							label: 'name',
							value: 'id',
							children: 'cityInfoList',
						},
						items: [...citysList],
					},
					{
						type: 'select',
						key: 'principalId',
						name: 'principalId',
						label: '主体名称',
						keys: 'id',
						title: 'name',
						items: [...mainCompany],
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'select',
						key: 'orderLocation',
						name: 'orderLocation',
						label: '订单位置',
						showSearch: true,
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.orderLocation],
					},
					{
						type: 'select',
						key: 'orderType',
						name: 'orderType',
						label: '订单类型',
						keys: 'code',
						title: 'name',
						items: [...orderType],
					},
					{
						type: 'input',
						key: 'orderNo',
						name: 'orderNo',
						label: '订单号',
					},
				],
			},
			{
				type: 'group',
				key: 'group3',
				groupItems: [
					{
						type: 'treeSelect',
						label: '公司',
						name: 'companyId',
						key: 'companyId',
						keys: 'id',
						title: 'name',
						treeData: [...orgSource],
					},
					{
						type: 'input',
						name: 'driverName',
						key: 'driverName',
						label: '司机姓名',
					},
					{
						type: 'input',
						name: 'carNo',
						key: 'carNo',
						label: '车牌号',
					},
				],
			},
		]
		setFormData(formItems)
	}, [citysList, orgSource, orderType, dict, mainCompany])

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_merchantCenter_awardSettlement_driverDetailList_listExport">
						<Button
							icon={<ArrowDownOutlined />}
							ghost
							size="small"
							className="btn_import"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '163',
									queryDesc: '奖励单导出,resourceId:163',
									queryParam: searchData,
								})
							}}>
							导出奖励单
						</Button>
					</Permissions>
					<Permissions permissionID="amc_merchantCenter_awardSettlement_driverDetailList_detailExport">
						<Button
							icon={<ArrowDownOutlined />}
							ghost
							size="small"
							className="btn_import"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '164',
									queryDesc: '奖励明细导出,resourceId:164',
									queryParam: searchData,
								})
							}}>
							导出奖励明细
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					params={params}
					columns={columns}
					pagination
					total={total}
					scroll={{y: 500}}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					kid="id"
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
		</div>
	)
}
export default connect(({user}: any) => ({
	user,
}))(subsidy)
